<template>
  <div class="workload-manager">
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="searchParams.npi" placeholder="请选择担当">
            <el-option v-for="item in npiList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="searchParams.project" placeholder="请选择项目名称">
            <el-option v-for="item in projectList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="searchParams.month"
            type="month"
            placeholder="选择月份"
            @change="handleMonthChange">
          </el-date-picker>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="success" @click="handleAdd" style="margin-left: 10px;">新增</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" style="margin-top: 20px;">
      <el-table
        :data="filteredWorkLoads"
        border
        style="width: 100%"
        @cell-dblclick="handleCellDblClick">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="npi" label="担当" width="120"></el-table-column>
        <el-table-column prop="phase" label="任务" width="180"></el-table-column>
        <el-table-column prop="remark" label="备注" width="180"></el-table-column>
        <el-table-column label="预计工时" width="120">
          <template slot-scope="scope">
            {{ calculateTotalWorkTime(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="depend" label="依赖人" width="120"></el-table-column>
        <el-table-column prop="dependTime" label="依赖时间" width="150"></el-table-column>
        <el-table-column prop="acceptance" label="初版纳期" width="150"></el-table-column>
        <el-table-column prop="reaccptance" label="更新纳期" width="150"></el-table-column>
        
        <!-- 月份日期列 -->
        <el-table-column 
          :label="day" 
          width="100"
          v-for="(day, index) in monthDays" 
          :key="index">
          <template slot-scope="scope">
            <div v-if="getWorkDataByDate(scope.row, day)">
              <div>
                <span v-if="getWorkDataByDate(scope.row, day).isbusy === '1'">上午</span>
                <span v-if="getWorkDataByDate(scope.row, day).isbusy === '2'">下午</span>
              </div>
              <div>{{ getWorkDataByDate(scope.row, day).workTime }}h</div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑/新增对话框 - 包含日历 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="800px"
      @close="handleDialogClose">
      <el-form :model="formData" ref="form" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 基本信息表单 -->
            <el-form-item label="担当" prop="npi">
              <el-select v-model="formData.npi" placeholder="请选择担当">
                <el-option v-for="item in npiList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目名称" prop="project">
              <el-select v-model="formData.project" placeholder="请选择项目名称">
                <el-option v-for="item in projectList" :key="item" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="任务" prop="phase">
              <el-input v-model="formData.phase"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formData.remark"></el-input>
            </el-form-item>
            <el-form-item label="依赖人" prop="depend">
              <el-input v-model="formData.depend"></el-input>
            </el-form-item>
            <el-form-item label="依赖时间" prop="dependTime">
              <el-date-picker v-model="formData.dependTime" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="初版纳期" prop="acceptance">
              <el-date-picker v-model="formData.acceptance" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="更新纳期" prop="reaccptance">
              <el-date-picker v-model="formData.reaccptance" type="date" placeholder="选择日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="月份" prop="month">
              <el-date-picker
                v-model="formData.month"
                type="month"
                placeholder="选择月份"
                @change="handleFormMonthChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <!-- 日历部分 - 作为表单的一部分 -->
            <el-card class="form-calendar">
              <div slot="header">
                <span>{{ formatMonth(formData.month) }} 工作安排</span>
                <div class="calendar-legend">
                  <div class="legend-item"><span class="legend-dot busy-dot"></span> 已选择</div>
                  <div class="legend-item"><span class="legend-dot morning-dot"></span> 上午</div>
                  <div class="legend-item"><span class="legend-dot afternoon-dot"></span> 下午</div>
                </div>
              </div>
              
              <div class="calendar-header">
                <div class="calendar-weekday">日</div>
                <div class="calendar-weekday">一</div>
                <div class="calendar-weekday">二</div>
                <div class="calendar-weekday">三</div>
                <div class="calendar-weekday">四</div>
                <div class="calendar-weekday">五</div>
                <div class="calendar-weekday">六</div>
              </div>
              
              <div class="calendar-grid">
                <div 
                  class="calendar-day empty" 
                  v-for="(empty, index) in firstDayOffset" 
                  :key="'empty-' + index">
                </div>
                
                <div 
                  class="calendar-day" 
                  v-for="(day, index) in monthDays" 
                  :key="day"
                  :class="{ 'today': isToday(day), 'weekend': isWeekend(day) }">
                  <div class="day-number">{{ day.split('-').slice(2).join('-') }}</div>
                  <div 
                    class="day-part morning"
                    :class="{ 'busy': isBusy(day, '1') }"
                    @click="handleDayPartClick(day, '1')"
                    @dblclick="handleDayPartDblClick(day, '1')">
                    <span v-if="getWorkTime(day, '1')">{{ getWorkTime(day, '1') }}h</span>
                  </div>
                  <div 
                    class="day-part afternoon"
                    :class="{ 'busy': isBusy(day, '2') }"
                    @click="handleDayPartClick(day, '2')"
                    @dblclick="handleDayPartDblClick(day, '2')">
                    <span v-if="getWorkTime(day, '2')">{{ getWorkTime(day, '2') }}h</span>
                  </div>
                </div>
              </div>
              
              <div class="total-worktime" v-if="calculateFormTotalWorkTime() > 0">
                <strong>总工时：</strong>{{ calculateFormTotalWorkTime() }}小时
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
      
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </el-dialog>

    <!-- 工时编辑对话框 -->
    <el-dialog
      title="编辑工时"
      :visible.sync="workTimeDialogVisible"
      width="300px">
      <el-form :model="workTimeForm" ref="workTimeForm" label-width="80px">
        <el-form-item label="工时" prop="workTime">
          <el-input type="number" v-model.number="workTimeForm.workTime" min="0" max="12"></el-input>
        </el-form-item>
        <div class="time-hint">提示：请输入0-12之间的工时数</div>
      </el-form>
      <div slot="footer">
        <el-button @click="workTimeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleWorkTimeSave">保存</el-button>
      </div>
    </el-dialog>

    <!-- 新增数据弹窗 -->
    <el-dialog
      title="新增数据详情"
      :visible.sync="newDataDialogVisible"
      width="600px">
      <pre>{{ JSON.stringify(newData, null, 2) }}</pre>
      <div slot="footer">
        <el-button @click="newDataDialogVisible = false">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WorkLoadManager',
  data() {
    return {
      // 查询参数
      searchParams: {
        npi: '',
        project: '',
        month: ''
      },
      
      // 数据列表
      workLoads: [
        {
          id: 1,
          npi: '谢',
          project: 'H处理',
          phase: '样式开发',
          remark: 'abc',
          depend: '小芳B',
          dependTime: '2025-07-17',
          acceptance: '2025-07-19',
          reaccptance: '2025-07-24',
          workData: '[{"workTime":"4", "workDate":"2025-07-17", "isbusy":"1"},{"workTime":"4", "workDate":"2025-07-18", "isbusy":"1"}]',
          state: 1
        },
        {
          id: 2,
          npi: '李',
          project: 'H处理',
          phase: '逻辑开发',
          remark: 'def',
          depend: '谢',
          dependTime: '2025-07-18',
          acceptance: '2025-07-20',
          reaccptance: '2025-07-25',
          workData: '[{"workTime":"6", "workDate":"2025-07-19", "isbusy":"2"},{"workTime":"8", "workDate":"2025-07-20", "isbusy":"1"}]',
          state: 1
        }
      ],
      
      // 担当列表
      npiList: ['谢', '李', '王', '赵'],
      
      // 项目列表
      projectList: ['H处理', 'M系统', 'P平台', 'Q工具'],
      
      // 月份天数
      monthDays: [],
      
      // 当月第一天是星期几（偏移量）
      firstDayOffset: 0,
      
      // 对话框状态
      dialogVisible: false,
      dialogTitle: '新增工作量',
      newDataDialogVisible: false, // 新增数据弹窗
      newData: null, // 新增的数据
      
      // 表单数据
      formData: {
        id: null,
        npi: '',
        project: '',
        phase: '',
        remark: '',
        depend: '',
        dependTime: '',
        acceptance: '',
        reaccptance: '',
        workData: '[]',
        state: 1,
        month: ''
      },
      
      // 表单验证规则
      formRules: {
        npi: [{ required: true, message: '请选择担当', trigger: 'change' }],
        project: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
        phase: [{ required: true, message: '请输入任务', trigger: 'blur' }],
        acceptance: [{ required: true, message: '请选择初版纳期', trigger: 'change' }],
        month: [{ required: true, message: '请选择月份', trigger: 'change' }]
      },
      
      // 工时编辑对话框
      workTimeDialogVisible: false,
      workTimeForm: {
        workTime: 0
      },
      currentWorkDate: '',
      currentWorkPart: ''
    };
  },
  computed: {
    // 过滤后的工作量数据
    filteredWorkLoads() {
      return this.workLoads.filter(item => {
        if (this.searchParams.npi && item.npi !== this.searchParams.npi) return false;
        if (this.searchParams.project && item.project !== this.searchParams.project) return false;
        return true;
      });
    }
  },
  methods: {
    // 处理月份变更
    handleMonthChange(date) {
      if (date) {
        this.generateMonthDays(date);
      }
    },
    
    // 处理表单中的月份变更
    handleFormMonthChange(date) {
      if (date) {
        this.generateMonthDays(date);
      }
    },
    
    // 生成月份的所有日期
    generateMonthDays(date) {
      const year = date.getFullYear();
      const month = date.getMonth();
      
      // 获取当月第一天
      const firstDay = new Date(year, month, 1);
      // 获取当月最后一天
      const lastDay = new Date(year, month + 1, 0);
      
      // 计算第一天是星期几（0是星期日）
      this.firstDayOffset = firstDay.getDay();
      
      // 生成当月所有日期
      this.monthDays = [];
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const day = new Date(year, month, i);
        this.monthDays.push(this.formatDate(day));
      }
    },
    
    // 格式化日期为yyyy-mm-dd
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 格式化月份显示
    formatMonth(date) {
      if (!date) return '';
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      return `${year}年${month}月`;
    },
    
    // 判断是否是今天
    isToday(day) {
      const today = this.formatDate(new Date());
      return day === today;
    },
    
    // 判断是否是周末
    isWeekend(day) {
      const date = new Date(day);
      const dayOfWeek = date.getDay();
      return dayOfWeek === 0 || dayOfWeek === 6;
    },
    
    // 处理查询
    handleSearch() {
      if (this.searchParams.month) {
        this.generateMonthDays(this.searchParams.month);
      }
    },
    
    // 处理新增
    handleAdd() {
      this.dialogTitle = '新增工作量';
      const now = new Date();
      this.formData = {
        id: null,
        npi: '',
        project: '',
        phase: '',
        remark: '',
        depend: '',
        dependTime: '',
        acceptance: '',
        reaccptance: '',
        workData: '[]',
        state: 1,
        month: now
      };
      this.dialogVisible = true;
      this.generateMonthDays(now);
    },
    
    // 处理保存
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let newData;
          if (this.formData.id) {
            // 编辑
            const index = this.workLoads.findIndex(item => item.id === this.formData.id);
            if (index !== -1) {
              this.workLoads[index] = { 
                ...this.formData,
                dependTime: this.formData.dependTime ? this.formatDate(this.formData.dependTime) : '',
                acceptance: this.formData.acceptance ? this.formatDate(this.formData.acceptance) : '',
                reaccptance: this.formData.reaccptance ? this.formatDate(this.formData.reaccptance) : ''
              };
              this.$message.success('修改成功');
            }
          } else {
            // 新增
            const newId = Math.max(...this.workLoads.map(item => item.id), 0) + 1;
            newData = {
              ...this.formData,
              id: newId,
              dependTime: this.formData.dependTime ? this.formatDate(this.formData.dependTime) : '',
              acceptance: this.formData.acceptance ? this.formatDate(this.formData.acceptance) : '',
              reaccptance: this.formData.reaccptance ? this.formatDate(this.formData.reaccptance) : ''
            };
            // 移除Date对象，避免JSON序列化问题
            delete newData.month;
            this.workLoads.push(newData);
            
            // 保存新增的数据用于弹窗显示
            this.newData = { ...newData };
            this.newDataDialogVisible = true;
          }
          this.dialogVisible = false;
        }
      });
    },
    
    // 处理对话框关闭
    handleDialogClose() {
      // 重置表单验证
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    
    // 处理表格单元格双击
    handleCellDblClick(row) {
      this.dialogTitle = '编辑工作量';
      this.formData = { ...row };
      // 处理日期类型
      this.formData.dependTime = row.dependTime ? new Date(row.dependTime) : '';
      this.formData.acceptance = row.acceptance ? new Date(row.acceptance) : '';
      this.formData.reaccptance = row.reaccptance ? new Date(row.reaccptance) : '';
      this.formData.month = row.dependTime ? new Date(row.dependTime) : new Date();
      this.dialogVisible = true;
      this.generateMonthDays(this.formData.month);
    },
    
    // 根据日期获取工作数据
    getWorkDataByDate(row, date) {
      try {
        const workData = JSON.parse(row.workData);
        return workData.find(item => item.workDate === date);
      } catch (e) {
        return null;
      }
    },
    
    // 计算总工时
    calculateTotalWorkTime(row) {
      try {
        const workData = JSON.parse(row.workData);
        return workData.reduce((total, item) => total + Number(item.workTime), 0);
      } catch (e) {
        return 0;
      }
    },
    
    // 计算表单中的总工时
    calculateFormTotalWorkTime() {
      try {
        const workData = JSON.parse(this.formData.workData);
        return workData.reduce((total, item) => total + Number(item.workTime), 0);
      } catch (e) {
        return 0;
      }
    },
    
    // 判断某天某时段是否忙碌
    isBusy(date, part) {
      try {
        const workData = JSON.parse(this.formData.workData);
        return workData.some(item => item.workDate === date && item.isbusy === part);
      } catch (e) {
        return false;
      }
    },
    
    // 获取某天某时段的工时
    getWorkTime(date, part) {
      try {
        const workData = JSON.parse(this.formData.workData);
        const data = workData.find(item => item.workDate === date && item.isbusy === part);
        return data ? data.workTime : null;
      } catch (e) {
        return null;
      }
    },
    
    // 处理日期时段点击（上午/下午）
    handleDayPartClick(date, part) {
      try {
        let workData = JSON.parse(this.formData.workData);
        // 检查是否已存在该日期和时段的记录
        const index = workData.findIndex(item => item.workDate === date && item.isbusy === part);
        
        if (index !== -1) {
          // 已存在则移除
          workData.splice(index, 1);
          this.$message.info(`已取消${date}${part === '1' ? '上午' : '下午'}的安排`);
        } else {
          // 不存在则添加
          workData.push({
            workTime: '4', // 默认4小时
            workDate: date,
            isbusy: part
          });
          this.$message.success(`已安排${date}${part === '1' ? '上午' : '下午'}`);
        }
        
        this.formData.workData = JSON.stringify(workData);
      } catch (e) {
        this.$message.error('操作失败');
        console.error(e);
      }
    },
    
    // 处理日期时段双击（编辑工时）
    handleDayPartDblClick(date, part) {
      this.currentWorkDate = date;
      this.currentWorkPart = part;
      this.workTimeForm.workTime = Number(this.getWorkTime(date, part) || 4);
      this.workTimeDialogVisible = true;
    },
    
    // 保存工时编辑
    handleWorkTimeSave() {
      try {
        let workData = JSON.parse(this.formData.workData);
        
        // 查找或添加工时记录
        const recordIndex = workData.findIndex(
          item => item.workDate === this.currentWorkDate && item.isbusy === this.currentWorkPart
        );
        
        if (recordIndex !== -1) {
          // 更新现有记录
          workData[recordIndex].workTime = this.workTimeForm.workTime.toString();
        } else {
          // 添加新记录
          workData.push({
            workTime: this.workTimeForm.workTime.toString(),
            workDate: this.currentWorkDate,
            isbusy: this.currentWorkPart
          });
        }
        
        // 保存更新后的数据
        this.formData.workData = JSON.stringify(workData);
        
        this.$message.success(`已保存${this.currentWorkDate}${this.currentWorkPart === '1' ? '上午' : '下午'}的工时为${this.workTimeForm.workTime}h`);
        this.workTimeDialogVisible = false;
      } catch (e) {
        this.$message.error('保存失败');
        console.error(e);
      }
    }
  },
  mounted() {
    // 默认选中当前月份
    const now = new Date();
    this.searchParams.month = now;
    this.generateMonthDays(now);
  }
};
</script>

<style scoped>
.workload-manager {
  padding: 20px;
}

/* 表单内日历样式 */
.form-calendar {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.calendar-header {
  display: flex;
  margin-bottom: 10px;
}

.calendar-weekday {
  flex: 1;
  text-align: center;
  font-weight: bold;
  padding: 5px 0;
  font-size: 12px;
  background-color: #f5f7fa;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
  flex-grow: 1;
}

.calendar-day {
  border: 1px solid #e6e6e6;
  min-height: 60px;
  position: relative;
  font-size: 12px;
}

.calendar-day.empty {
  border: none;
}

.day-number {
  position: absolute;
  top: 3px;
  right: 3px;
  font-size: 11px;
  color: #666;
}

.day-part {
  height: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
}

.day-part.morning {
  border-bottom: 1px dashed #e6e6e6;
}

.day-part.busy {
  background-color: #e1f5fe;
}

.day-part:hover {
  background-color: #f5f7fa;
}

.calendar-day.today {
  border-color: #409eff;
}

.calendar-day.weekend {
  background-color: #f9f9f9;
}

.total-worktime {
  margin-top: 10px;
  padding: 5px;
  text-align: right;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 日历图例 */
.calendar-legend {
  display: flex;
  font-size: 12px;
  margin-top: 5px;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
}

.legend-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
}

.busy-dot {
  background-color: #409eff;
}

.morning-dot {
  background-color: #67c23a;
}

.afternoon-dot {
  background-color: #e6a23c;
}

/* 工时提示 */
.time-hint {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
  text-align: right;
}
</style>
